<?php
require_once('cps360.config.php');
require_once('func.php');

$cps360_info = array();

$post = $_POST;

$cps360_info['bid'] = $post['bid'];
$cps360_info['qihoo_id'] = $post['qihoo_id'];
$cps360_info['url'] = $post['url'];
$cps360_info['from'] = $post['from'];
$cps360_info['active_time'] = $post['active_time'];
$cps360_info['ext'] = $post['ext'];
$cps360_info['qid'] = $post['qid'];
$cps360_info['qmail'] = $post['qmail'];
$cps360_info['qname'] = $post['qname'];
$cps360_info['sign'] = $post['sign'];

$now_time = time();

// 保存cps信息
$cookie_info = array('cookie_time'=>$now_time);
foreach ($cps360_info as $key=>&$value)
{
    if ($key != 'sign') {
        $cookie_info[$key] = urlencode($value);
    }
}
setcookie('cps360', serialize($cookie_info), $now_time+60*60*24*CPS360_RD, '/');

//检查是否超时
$timeCheck = checkActiveTime($cps360_info['active_time'], $msg);

// 签名验证
$sign_check = $cps360_info['bid'];
$sign_check .= '#'.$cps360_info['active_time'];
$sign_check .= '#'.CPS360_CP_KEY;
$sign_check .= '#'.$cps360_info['qid'];
$sign_check .= '#'.$cps360_info['qmail'];
$sign_check .= '#'.$cps360_info['qname'];
$sign_check = md5($sign_check);
if (!$timeCheck ||
    $cps360_info['sign'] != $sign_check)
{
    $from_ip = getFromIp();

    // 超时或者签名验证失败
    $error_data = array(
        'bid' => CPS360_BID,
        'active_time' => $now_time,
        'sign' => md5(CPS360_BID . "#" . $now_time . "#" . CPS360_CP_KEY),
        'pre_active_time' => $cps360_info['active_time'],
        'pre_active_time' => $cps360_info['active_time'],
        'pre_sign' => $cps360_info['sign'],
        'qid' => $cps360_info['qid'],
        'qname' => $cps360_info['qname'],
        'qmail' => $cps360_info['qmail'],
        'from_url' => $cps360_info['from_url'],
        'from_ip' => $from_ip
    );

    curlRequest(CPS360_FAILED_URL, $error_data);
} else {
    $qid = $cps360_info['qid'];
    if ($qid) {
        // 用户自动登录 TODO
    }
}

Header('Location:'.urldecode($cps360_info['url']));

?>
